package com.cloudcc.boot.utils.util;

import com.cloudcc.boot.constants.UtilConstants;
import com.cloudcc.boot.model.UserInfo;
import com.cloudcc.client.CCObject;
import com.cloudcc.service.CCWService;
import com.cloudcc.service.ServiceCaller;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class CCServiceClass {
    public CCWService cs ;
    public String binding;
    String app_base_url= UtilConstants.Public.CLOUDCCIP;
    public CCServiceClass (String bindingcontent) {
        ServiceCaller sc = new ServiceCaller(app_base_url);
        cs = sc.getSvcMan();
        binding = bindingcontent;
        cs.setBinding(binding);
    }

    /**
     * post连接
     * **/
    public  String httpOperate(String data_str) throws Exception{ //连接cloudcc系统(post)

        URL url = new URL(app_base_url+"/distributor.action");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST"); //post  方式请求
        String sc = "";
        String st = "";
        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(),"utf-8");
        out.write(data_str);
        out.close();
        if (con.getResponseCode() == 200){
            //System.out.println("---------服务器连接成功-------");
            InputStream is = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            while ((sc = br.readLine()) != null) {
                st = st + sc;
            }
        }else{
            System.out.println("---------服务器连接失败-------");
        }
        return st;
    }
    public void execute(){


    }

    public List<CCObject> cquery(String apiName) {
        List<Map> rst = cs.cqueryUg(apiName,"1=1",binding);
        List<CCObject> orst=  new ArrayList<CCObject>();
        for(Map m : rst) {
            CCObject co = new CCObject(apiName);
            for (Object _key : m.keySet()) {
                String key = (String)_key;
                co.put(key,m.get(key));
            }
            orst.add(co);
        }
        return orst;
    }

    public List<CCObject> cquery(String apiName, String expression) {
        List<Map> rst = cs.cqueryUg(apiName,expression,binding);
        List<CCObject> orst=  new ArrayList<CCObject>();
        for(Map m : rst) {
            CCObject co = new CCObject(apiName);
            for (Object _key : m.keySet()) {
                String key = (String)_key;
                co.put(key,m.get(key));
            }
            orst.add(co);
        }
        return orst;
    }
    public List<CCObject> cquery(String apiName, String expression,String orderbyExp) {
        List<Map> rst = cs.cqueryUg(apiName,expression+orderbyExp,binding);
        List<CCObject> orst=  new ArrayList<CCObject>();
        for(Map m : rst) {
            CCObject co = new CCObject(apiName);
            for (Object _key : m.keySet()) {
                String key = (String)_key;
                co.put(key,m.get(key));
            }
            orst.add(co);
        }
        return orst;
    }

    public ServiceResult insert(CCObject obj) throws Exception {
        String id = cs.insertUg(obj,binding);
//		JSONObject data = new JSONObject();
//		for (Object _key : obj.keySet()) {
//			String key = (String)_key;
//			data.put(key, obj.get(key));
//		}
//		JSONArray dataArray = new JSONArray();
//		dataArray.add(data);
//		StringBuffer sb = new StringBuffer();
//		sb.append("serviceName=insert");
//		sb.append("&objectApiName="+obj.getObjectApiName());
//		sb.append("&binding="+this.binding);
//		sb.append("&data="+dataArray.toString());
//		String rst = OperationService.operate("https://ccws.cloudcc.com/distributor.action", sb.toString());
//		System.out.println(rst);
        ServiceResult sr = new ServiceResult();
        if (id.length() == 20) {
            sr.put("id", id);
            sr.put("success", "true");
        } else {
            sr.put("id", "");
            sr.put("success", "false");
        }
//		System.out.println("插入完成："+id);
        return  sr;
    }

    public String update(CCObject cobj) {
        return cs.updateUg(cobj,binding);
    }
    public void update(List<CCObject> cobj) {
        for (CCObject co : cobj) {
            cs.updateUg(co,binding);
        }
    }
    public List<CCObject> cqlQuery(String apiName, String expression) {
        List<Map> rst =  cs.cqlQueryUg(apiName,expression,binding);
        List<CCObject> orst=  new ArrayList<CCObject>();
        for(Map m : rst) {
            CCObject co = new CCObject(apiName);
            for (Object _key : m.keySet()) {
                String key = (String)_key;
                co.put(key,m.get(key));
            }
            orst.add(co);
        }
        return orst;
    }


    public String  queryField(String ccAPI,String expression,String field) throws Exception{
        String param = "serviceName=cquery&objectApiName=" + ccAPI + "&expressions=" + expression + "&binding="+ this.binding;
        String value = "";//返回值
        JSONObject data_result1 = JSONObject.fromObject(this.httpOperate(param));
        String date1 = data_result1.get("data") == null ? "" : data_result1.getString("data");
        JSONArray dataArray1 = new JSONArray();
        if (StringUtils.isNotBlank(date1)) {
            dataArray1 = JSONArray.fromObject(date1);
        }
        if(dataArray1.size()>0){
            JSONObject obj1 = dataArray1.getJSONObject(0);
            value = obj1.getString(field)==null?"":String.valueOf(obj1.get(field));//ownerid
            //System.out.println("obj1"+obj1.toString());
            //System.err.println("obj1>>>"+value);
        }
        return value;
    }

    public void insert(List<CCObject> insertList) throws Exception{
        for (CCObject co : insertList ){
            insert(co);
        }
    }
    public ServiceResult insert (String objectApiName,JSONObject data) {
        ServiceResult sr = new ServiceResult();
        OperationService os = new OperationService();
        StringBuffer sb = new StringBuffer();
        sb.append("serviceName=insert");
        sb.append("&objectApiName="+objectApiName);
        sb.append("&binding="+this.binding);
        sb.append("&data=["+data +"]");
        try {
            String rst = os.operate(app_base_url+"/distributor.action", sb.toString());
            JSONObject rstObj = JSONObject.fromObject(rst);
            for (Object _key : rstObj.keySet()) {
                String key = (String)_key;
                sr.put(key, rstObj.get(key));
            }
        } catch (Exception e) {
            sr.put("result", "false");
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            sr.put("data", "{\"ids\":[]}");
            e.printStackTrace();
        }
        return sr;
    }
    public ServiceResult batchInsert(String objectApiName,List<JSONObject> datalist) {
        ServiceResult sr = new ServiceResult();
        try {
            List<Map> recordList = new ArrayList<Map>();
            for (JSONObject data : datalist) {
                Map<String,Object> record = new HashMap<String,Object>();
                record.put("CCObjectAPI", objectApiName);
                for (Object _key : data.keySet()) {
                    String key = (String)_key;
                    record.put(key, data.get(key));
                }
                recordList.add(record);
            }
            //log.info(recordList);
            log.info(binding);
            String rst = cs.batchInsertUg(recordList, this.binding);
            log.info(rst);
        } catch (Exception e) {
            sr.put("result", "false");
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            sr.put("data", "{\"ids\":[]}");
            e.printStackTrace();
        }
        return sr;
    }
    /**
     * @author caoyx
     * @param objectApiName 对象名称
     * @param datalist 批量数据
     * @return
     * @throws UnsupportedEncodingException
     */
    public ServiceResult insertList (String objectApiName,List<JSONObject> datalist) throws UnsupportedEncodingException {
        ServiceResult sr = new ServiceResult();
        OperationService os = new OperationService();
        StringBuffer sb = new StringBuffer();
        sb.append("serviceName=insert");
        sb.append("&objectApiName="+objectApiName);
        sb.append("&binding="+this.binding);
        sb.append("&data="+URLEncoder.encode(datalist.toString(),"utf-8"));
        try {
            String rst = os.operate(app_base_url+"/distributor.action", sb.toString());
            JSONObject rstObj = JSONObject.fromObject(rst);
            for (Object _key : rstObj.keySet()) {
                String key = (String)_key;
                sr.put(key, rstObj.get(key));
            }
            //log.info(rst);
        } catch (Exception e) {
            sr.put("result", "false");
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            sr.put("data", "{\"ids\":[]}");
            e.printStackTrace();
        }
        return sr;
    }

    /**
     * 不触发触发器的新增
     * @param objectApiName
     * @param datalist
     * @return
     * @throws UnsupportedEncodingException
     */
    public ServiceResult insertListLt (String objectApiName,List<JSONObject> datalist) throws UnsupportedEncodingException {
        ServiceResult sr = new ServiceResult();
        OperationService os = new OperationService();
        StringBuffer sb = new StringBuffer();
        sb.append("serviceName=insertLt");
        sb.append("&objectApiName="+objectApiName);
        sb.append("&binding="+this.binding);
        sb.append("&data="+URLEncoder.encode(datalist.toString(),"utf-8"));
        try {
            String rst = os.operate(app_base_url+"/distributor.action", sb.toString());
            JSONObject rstObj = JSONObject.fromObject(rst);
            for (Object _key : rstObj.keySet()) {
                String key = (String)_key;
                sr.put(key, rstObj.get(key));
            }
            //log.info(rst);
        } catch (Exception e) {
            sr.put("result", "false");
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            sr.put("data", "{\"ids\":[]}");
            e.printStackTrace();
        }
        return sr;
    }
    /**
     * @author caoyx
     * @param objectApiName
     * @param datalist
     * @return {returnCode=-1,
     * 			result=false,
     * 			returnInfo=java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
     * 		   }
     * @throws UnsupportedEncodingException
     */
    public ServiceResult updateList (String objectApiName,List<JSONObject> datalist) throws UnsupportedEncodingException {
        ServiceResult sr = new ServiceResult();
        OperationService os = new OperationService();
        StringBuffer sb = new StringBuffer();
        sb.append("serviceName=update");
        sb.append("&objectApiName="+objectApiName);
        sb.append("&binding="+this.binding);
        sb.append("&data="+URLEncoder.encode(datalist.toString(),"utf-8"));
        try {
            System.out.println(app_base_url+"/distributor.action");
            String rst = os.operate(app_base_url+"/distributor.action", sb.toString());
            JSONObject rstObj = JSONObject.fromObject(rst);
            for (Object _key : rstObj.keySet()) {
                String key = (String)_key;
                sr.put(key, rstObj.get(key));
            }
        } catch (Exception e) {
            sr.put("result", false);
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            e.printStackTrace();
        }
        return sr;
    }

    /**
     * 批量更新 不触发触发器
     * @param objectApiName
     * @param datalist
     * @return
     * @throws UnsupportedEncodingException
     */
    public ServiceResult updateListLt (String objectApiName,List<JSONObject> datalist) throws UnsupportedEncodingException {
        ServiceResult sr = new ServiceResult();
        OperationService os = new OperationService();
        StringBuffer sb = new StringBuffer();
        sb.append("serviceName=updateLt");
        sb.append("&objectApiName="+objectApiName);
        sb.append("&binding="+this.binding);
        sb.append("&data="+URLEncoder.encode(datalist.toString(),"utf-8"));
        try {
            System.out.println(app_base_url+"/distributor.action");
            String rst = os.operate(app_base_url+"/distributor.action", sb.toString());
            JSONObject rstObj = JSONObject.fromObject(rst);
            for (Object _key : rstObj.keySet()) {
                String key = (String)_key;
                sr.put(key, rstObj.get(key));
            }
        } catch (Exception e) {
            sr.put("result", false);
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            e.printStackTrace();
        }
        return sr;
    }

    /**
     * 更新单条数据
     * @param objectApiName
     * @param data
     * @return
     * @throws UnsupportedEncodingException
     */
    public ServiceResult update (String objectApiName,JSONObject data) throws UnsupportedEncodingException {
        ServiceResult sr = new ServiceResult();
        OperationService os = new OperationService();
        StringBuffer sb = new StringBuffer();
        sb.append("serviceName=update");
        sb.append("&objectApiName="+objectApiName);
        sb.append("&binding="+this.binding);
        sb.append("&data= ["+URLEncoder.encode(data.toString(),"utf-8")+"]");
        try {
            //System.out.println(app_base_url+"/distributor.action");
            String rst = os.operate(app_base_url+"/distributor.action", sb.toString());
            JSONObject rstObj = JSONObject.fromObject(rst);
            for (Object _key : rstObj.keySet()) {
                String key = (String)_key;
                sr.put(key, rstObj.get(key));
            }
        } catch (Exception e) {
            sr.put("result", false);
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            e.printStackTrace();
        }
        return sr;
    }

    /**
     * 更新单条数据不触发触发器
     * @param objectApiName
     * @param data
     * @return
     * @throws UnsupportedEncodingException
     */
    public ServiceResult updateLt (String objectApiName,JSONObject data) throws UnsupportedEncodingException {
        ServiceResult sr = new ServiceResult();
        OperationService os = new OperationService();
        StringBuffer sb = new StringBuffer();
        sb.append("serviceName=updateLt");
        sb.append("&objectApiName="+objectApiName);
        sb.append("&binding="+this.binding);
        sb.append("&data= ["+URLEncoder.encode(data.toString(),"utf-8")+"]");
        try {
            //System.out.println(app_base_url+"/distributor.action");
            String rst = os.operate(app_base_url+"/distributor.action", sb.toString());
            JSONObject rstObj = JSONObject.fromObject(rst);
            for (Object _key : rstObj.keySet()) {
                String key = (String)_key;
                sr.put(key, rstObj.get(key));
            }
        } catch (Exception e) {
            sr.put("result", false);
            sr.put("returnInfo", e.toString());
            sr.put("returnCode", "");
            e.printStackTrace();
        }
        return sr;
    }

    public String delete(CCObject bjdmx) {
        return cs.deleteUg(bjdmx,binding);
    }
    public void insertDataBySql(String tableName,List<JSONObject> datalist) {
        String sql1 = "select A.column_name apiname, A.data_type datatype" +
                " FROM USER_TAB_COLUMNS A " +
                "where table_name = upper('"+tableName+"') ORDER BY column_id asc";
        List<Map> fieldList = cs.cqlQuery("Account",sql1);

        for (JSONObject item : datalist) {
            StringBuffer sql = new StringBuffer();
            StringBuffer values = new StringBuffer();
            String update_sql = "";
            String fields_list = "";
            String value_list = "";
            sql.append("merge into "+tableName+" t0 using (select ");
            for (int i=0;i<fieldList.size();i++) {
                Map field = fieldList.get(i);
                String datatype = (String)field.get("datatype");
                String apiname =  (String)field.get("apiname");
                apiname = apiname.toLowerCase();
                String value = (String) item.get(apiname);
                if (value == null) {
                    continue;
                }

                fields_list += apiname+",";
                if ("DATE".equals(datatype)) {
                    values.append("to_date('"+item.get(apiname)+"','yyyy-mm-dd hh24:mi:ss') as "+apiname+",");
                    value_list += "to_date('"+item.get(apiname)+"','yyyy-mm-dd hh24:mi:ss'),";
                } else {
                    values.append("'"+item.get(apiname)+"' as "+apiname+",");
                    value_list += "'" + item.get(apiname)+"',";
                }
                if (!"id".equals(apiname)) {
                    update_sql += "t0."+apiname+"=t1."+apiname+",";
                }
            }

            String val = values.toString();
            if (val.indexOf(",") != -1) {
                fields_list = fields_list.substring(0,fields_list.lastIndexOf(","));
                val = val.substring(0,val.lastIndexOf(","));
                update_sql = update_sql.substring(0,update_sql.lastIndexOf(","));
                value_list = value_list.substring(0,value_list.lastIndexOf(","));
            }

            String total_sql = sql.toString() + val+" from dual) t1 on (t0.id=t1.id) when matched then update set "+update_sql+" WHEN NOT MATCHED THEN insert("+fields_list+")values("+value_list+")";
            cs.cqlQuery(tableName, total_sql);
        }
        //cs.cqlQuery(tableName, sql.toString());
    }



    public void insertAttachment( List<JSONObject> dataList) {
        try {
            // TODO Auto-generated method stub
            for (JSONObject attachement : dataList) {
                Map data = new HashMap<String,Object>();
                for (Object _key : attachement.keySet()) {
                    String key = (String)_key;
                    data.put(key,attachement.get(key));
                }
                String suffix = (String)attachement.get("suffix");
                String fileId = (String)attachement.get("id");
                cqlQuery("attachement","delete from tp_sys_attachement where id='"+fileId+"'");
                String attachement_file_path = "";
                String newFileId = this.uploadFile(data, file2Byte(attachement_file_path));
                cqlQuery("attachement","update tp_sys_attachement set id='"+fileId+"' where id='"+newFileId+"'");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public String uploadFile(Map data,byte[] file) {
        String rst = cs.uploadFileFromByte(data, file);
        return rst;
    }
    /**
     * 获得指定文件的byte数组
     * @param filePath 文件绝对路径
     * @return
     */
    public static byte[] file2Byte(String filePath){
        ByteArrayOutputStream bos=null;
        BufferedInputStream in=null;
        try{
            File file=new File(filePath);
            if(!file.exists()){
                throw new FileNotFoundException("file not exists");
            }
            bos=new ByteArrayOutputStream((int)file.length());
            in=new BufferedInputStream(new FileInputStream(file));
            int buf_size=1024;
            byte[] buffer=new byte[buf_size];
            int len=0;
            while(-1 != (len=in.read(buffer,0,buf_size))){
                bos.write(buffer,0,len);
            }
            return bos.toByteArray();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
            return null;
        }
        finally{
            try{
                if(in!=null){
                    in.close();
                }
                if(bos!=null){
                    bos.close();
                }
            }
            catch(Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public void insertSystblBySql(String tableName, List<JSONObject> datalist) {
        String sql1 = "select A.column_name apiname, A.data_type datatype" +
                " FROM USER_TAB_COLUMNS A " +
                "where table_name = upper('"+tableName+"') ORDER BY column_id asc";
        List<Map> fieldList = cs.cqlQuery("Account",sql1);

        for (JSONObject item : datalist) {
            StringBuffer sql = new StringBuffer();
            StringBuffer values = new StringBuffer();
            String update_sql = "";
            String fields_list = "";
            String value_list = "";
            sql.append("merge into "+tableName+" t0 using (select ");
            for (int i=0;i<fieldList.size();i++) {
                Map field = fieldList.get(i);
                String datatype = (String)field.get("datatype");
                String apiname =  (String)field.get("apiname");
                apiname = apiname.toLowerCase();
                String value = (String) item.get(apiname);
                if (value == null) {
                    continue;
                }

                fields_list += apiname+",";
                if ("DATE".equals(datatype)) {
                    values.append("to_date('"+item.get(apiname)+"','yyyy-mm-dd hh24:mi:ss') as "+apiname+",");
                    value_list += "to_date('"+item.get(apiname)+"','yyyy-mm-dd hh24:mi:ss'),";
                } else {
                    values.append("'"+item.get(apiname)+"' as "+apiname+",");
                    value_list += "'" + item.get(apiname)+"',";
                }
                if (!"id".equals(apiname)) {
                    update_sql += "t0."+apiname+"=t1."+apiname+",";
                }
            }

            String val = values.toString();
            if (val.indexOf(",") != -1) {
                fields_list = fields_list.substring(0,fields_list.lastIndexOf(","));
                val = val.substring(0,val.lastIndexOf(","));
                update_sql = update_sql.substring(0,update_sql.lastIndexOf(","));
                value_list = value_list.substring(0,value_list.lastIndexOf(","));
            }

            String total_sql = sql.toString() + val+" from dual) t1 on (t0.id=t1.id) when matched then update set "+update_sql+" WHEN NOT MATCHED THEN insert("+fields_list+")values("+value_list+")";
            cs.cqlQuery(tableName, total_sql);
        }
    }
    public static void main(String[] args) {
        UserInfo uinfo = new UserInfo();
        uinfo.put("userName","admin@ceyear.com");
        uinfo.put("password","ceyear2019");
        CCService cs = new CCService(uinfo);
        List<CCObject>datalist = cs.cquery("salsorderdetail","exists(select t.id from salesorder t where t.id=t0.salsorderid and t.id='a202019A3E5B415Fk6TZ')");
        System.out.println(datalist.size());
    }
}